package controller

import (
	"log"
	"regexp"
	"writerhelper/dao"
	"writerhelper/model"
	"writerhelper/service"

	"github.com/gin-gonic/gin"
)

type UserController struct {

}

func (uc *UserController) UserController(c *gin.RouterGroup){
	//登录
	c.POST("login", uc.Login)
}

func (uc *UserController) Login(c *gin.Context)  {
	var user model.User
	if err := c.Bind(&user);err != nil{
		log.Fatal("绑定错误，请核对", err)
	}
	//	检查前端数据是否合法
	checked := uc.checkFormData(&user)
	if !checked {
		log.Fatal("邮箱不符合要求")
	}
	//检查数据库是否有该用户
	if isPresence := dao.IsRegister(&user); isPresence{
		//创建token
		token := service.GenerateJwt(&user)
		c.JSON(200,gin.H{
			"code":"200",
			"message":"登录成功！",
			"token":token,
		})
	}else{
		c.JSON(200,gin.H{
			"code":"200",
			"message":"用户不存在",

		})
	}


	//	返回信息
}

func (uc *UserController)checkFormData(u *model.User) bool {
	myRegexp := `^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`
	match, _ :=regexp.MatchString(myRegexp, u.Email)
	if !match {
		return false
	}
	return true
}